#!/bin/bash

set -eu #x

CC="${CC:=cc}"
# -fverbose-asm -save-temps -Wno-sign-conversion -Wconversion
: ${FLAGS:='-ftrapv -O0 -g'}
CFLAGS_BUILD="${CFLAGS:=$FLAGS}"
PROJ_LDFLAGS="${LDFLAGS:=$FLAGS}"

# -Wno-type-limits
CFLAGS_WARN='-Wshadow -Wextra  -Wmissing-format-attribute'
CFLAGS_ALWAYS='-Wall -Wfloat-equal -fdiagnostics-show-option -Werror-implicit-function-declaration -Werror=return-type'
CFLAGS="${CFLAGS_WARN} ${CFLAGS_ALWAYS} ${CFLAGS_BUILD}"
PROJ_CFLAGS="$(getconf LFS_CFLAGS) -std=gnu99 -D_GNU_SOURCE -DCPFS_SIMD_ALIGNED -DCPFS_USE_SSSE3 ${CFLAGS}"
FUSE_CFLAGS="$(pkg-config --cflags fuse) -DFUSE_USE_VERSION=28"
FUSE_LDFLAGS=$(pkg-config --libs fuse)

function my_mktemp() {
    p=$(mktemp -t "${1}.$$.XXX")
    test $? -eq 0 || exit 1
    echo $p
}

echo CFLAGS=$CFLAGS_BUILD
echo LDFLAGS=$LDFLAGS

# create static library
libcpfs_objs=()
for src in cpfs.c log.c popcnt.c ssse3_popcount.c blkcache.c context.c types.c device.c; do
    obj=$(my_mktemp "${src}.o")
    libcpfs_objs[${#libcpfs_objs[*]}]="${obj}"
    "$CC" -c "${src}" -o "${obj}" ${PROJ_CFLAGS}
done
unset src obj
libcpfs_a=$(my_mktemp "libcpfs.a")
echo $libcpfs_a
rm "$libcpfs_a" && ar rcs "${libcpfs_a}" ${libcpfs_objs[*]}
#ar rus "${libcpfs_a}" ${libcpfs_objs[*]}

# mount.cpfs
echo mount.cpfs
"$CC" -o mount.cpfs mount.cpfs.c cpfsfuse.c "$libcpfs_a" ${FUSE_CFLAGS} ${PROJ_CFLAGS} ${FUSE_LDFLAGS} ${PROJ_LDFLAGS}

# mkfs.cpfs
echo mkfs.cpfs
"$CC" -o mkfs.cpfs mkfs.cpfs.c "$libcpfs_a" -lrt ${PROJ_CFLAGS} ${PROJ_LDFLAGS}

# systest
echo systest
"$CC" -o systest systest.c ${PROJ_CFLAGS} ${PROJ_LDFLAGS}

echo Completed build

#if [ $# -eq 1 ]
#then
#fi
